#!/usr/bin/python
# -*- coding: UTF-8 -*-
import scrapy
import json
import re
from seasonSpider.dbHelper import dbHelper

class AqiyiSpider(scrapy.Spider):
	
	name = "aqiyi"
	allowed_domains = ["aqiyi.org"]
	start_urls = [
		"https://www.iqiyi.com/v_19rr5qzzg4.html",
		"https://www.iqiyi.com/v_19rr5bqof0.html",
		"https://www.iqiyi.com/v_19rr5c08b8.html",
		"https://www.iqiyi.com/v_19rr5a1lx4.html",
		"https://www.iqiyi.com/v_19rr5a0df0.html",
		"https://www.iqiyi.com/v_19rrek0xfo.html",
		"https://www.iqiyi.com/v_19rr5iygds.html",
		"https://www.iqiyi.com/v_19rrc0apa4.html"

    ]

	weekList = [u"一",u"二",u"三",u"四",u"五",u"六",u"日"]

	def parse(self, response):
		filename = "aqiyi.log"
		with open(filename, 'wb') as f:
			f.write(response.body)

		#print(response.xpath('//a[contains(@class,"intro-img-link")]/img/@src').extract())
		#print(response.xpath('//div[contains(@class,"qy-episode-update")]/p/text()').extract())
		#print(response.xpath('//meta[contains(@name,"irAlbumName")]/@content').extract())

		name = response.xpath('//meta[contains(@name,"irAlbumName")]/@content').extract()[0]
		#print(name)
		info = response.xpath('//div[contains(@class,"qy-episode-update")]/p/text()').extract()[0]
		#print(info)
		strfindstart = u"更新至"
		strfindend = u"集"
		indexStart = info.find(strfindstart)
		indexEnd = info.find(strfindend,indexStart)
		if indexStart != -1:	
			pub_index = u"第" + info[indexStart+len(strfindstart):indexEnd] + u"话"
		else:
			pub_index = 0

		strfindweek = u"每周"
		indexWeek = info.find(strfindweek)
		if indexWeek != -1:	
			weekName = info[indexWeek+len(strfindweek):indexWeek+len(strfindweek)+1]
			week = self.weekList.index(weekName) + 1
		else:
			week = 0

		delay = 0
		season_status = 0
		imgUrl = response.xpath('//a[contains(@class,"intro-img-link")]/img/@src').extract()[0]
		imgUrl = imgUrl.replace("180_236","128_128",1)
		cover = imgUrl
		square_cover = imgUrl
		print(imgUrl)
		pl = 2
		dbHelper.updata_season(name,pub_index,week,delay,season_status,cover,square_cover,pl)
		# js = json.loads(response.body)
		# for resultItem in js["result"]:
		# 	week = resultItem["day_of_week"]
		# 	for seasonItem in resultItem["seasons"]:
		# 		week = week
		# 		name = seasonItem["title"]
		# 		cover = seasonItem["cover"]
		# 		square_cover = seasonItem["square_cover"]
		# 		delay = seasonItem["delay"]
		# 		season_status = seasonItem["season_status"]
		# 		if delay == 0:
		# 			pub_index = seasonItem["pub_index"]
		# 		else:
		# 			pub_index = seasonItem["delay_index"]
		# 		pl = 1
		# 		dbHelper.updata_season(name,pub_index,week,delay,season_status,cover,square_cover,pl)